<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>打印页面 - {{ room_number }}号监室</title>
    <style>
        @page {
            size: A4 landscape;
            margin: 0.1cm;
        }
        
        * {
            box-sizing: border-box;
            margin: 0;
            padding: 0;
        }
        
        body {
            font-family: 'SimSun', 'Microsoft YaHei', sans-serif;
            background: white;
            color: black;
            width: 100%;
            height: 100%;
        }
        
        .print-container {
            width: 297mm;
            height: 200mm;
            display: grid;
            grid-template-columns: 30% 30% 40%;
            grid-template-rows: 50% 50%;
            gap: 1px;
            padding: 1px;
            box-sizing: border-box;
            page-break-after: always;
        }

        /* 内容区域样式 */
        .tab-content {
            display: block;
            width: 100%;
            flex:1;
        }

        .section-header {
            font-weight: bold;
            font-size: 20px;
            text-align: center;
            margin:0，auto;
            padding: 2px;
            background-color: #f0f0f0;
            border-radius: 4px;
            height: max-content;
        }
        
        /* 座位区样式 - 第1列跨1-2行 */
        .seat-section {
            grid-column: 1;
            grid-row: 1 / span 2;
            max-height: 100%;
            border: 1px solid #000;
            padding: 10px;
            overflow: hidden;
        }
        
        .seat {
            display: grid;
            grid-template-columns: 60% 10% 30%;
            grid-template-rows: 10% 90%;
            min-height: 170mm;
            max-height: 718;            
            position: relative;
            overflow: visible;
            margin-top: 10px;
        }

        .seat .area {
            border: 1px solid #ddd;
            padding: 5px;
            position: relative;
            border-radius: 4px;
            font-size: 25px;
        }
        
        .seat1-area {
            grid-column: 1;
            grid-row: 2;
            background: #fff8e1;
            display: grid;
            grid-template-columns: repeat(3, minmax(0, 1fr));
            grid-template-rows: repeat(9, minmax(0, 1fr));
            gap: 5px;
        }

        /* 大人数模式下的座位区样式 */
        .seat1-area.large-mode {
            grid-template-columns: repeat(3, minmax(0, 1fr));
            grid-template-rows: repeat(11, minmax(0, 1fr));
        }

        .seat2-area {
            grid-column: 3;
            grid-row: 2;
            background: #e0f7fa;
            display: grid;
            grid-template-columns: repeat(1, minmax(0, 1fr));
            grid-template-rows: repeat(9, minmax(0, 1fr));
            gap: 5px;
        }

        /* 大人数模式下的座位区样式 */
        .seat2-area.large-mode {
            grid-template-columns: repeat(2, minmax(0, 1fr));
            grid-template-rows: repeat(9, minmax(0, 1fr));
        }
        
        .tunnel-area {
            grid-column: 2;
            grid-row: 1 / 3;
            background: #f5f5f5;
            display: flex;
            align-items: center;
            justify-content: center;
        }

        .box-area {
            grid-column: 3;
            grid-row: 1;
            background: #fce4ec;
            display: flex;
            align-items: center;
            justify-content: center;
        }
        .wash-area {
            grid-column: 1;
            grid-row: 1;
            background: #e3f2fd;
            display: flex;
            align-items: center;
            justify-content: center;
        }
        
        /* 铺位区样式 - 第2列跨1-2行 */
        .bed-section {
            grid-column: 2;
            grid-row: 1 / span 2;
            border: 1px solid #000;
            padding: 10px;
            overflow: hidden;
            max-height: 100%;
        }
        
        .bed {
            display: grid;
            grid-template-columns: 40% 60%;
            grid-template-rows: 20% 80%;
            min-height: 170mm;            
            position: relative;
            overflow: visible;
            margin-top: 10px;
        }
        
        .bed .area {
            border: 1px solid #ddd;
            margin: 2px;
            padding: 5px;
            position: relative;
            font-size: 25px;
            text-align: center;
        }
        
        .bed1-area {
            grid-column: 1;
            grid-row: 2;
            background: #fff8e1;
            display: grid;
            grid-template-columns: repeat(1, minmax(0, 1fr));
            grid-template-rows: repeat(13, minmax(0, 1fr));
            gap: 4px;
        }

        /* 大人数模式下的铺位区样式 */
        .bed1-area.large-mode {
            grid-template-rows: repeat(15, minmax(0, 1fr));
        }
        
        .bed2-area {
            grid-column: 2;
            grid-row: 1;
            background: #fff8e1;
            display: grid;
            grid-template-columns: repeat(1, minmax(0, 1fr));
            grid-template-rows: repeat(3, 1fr);
            gap: 4px;
            padding: 8px 10px;
        }

        .bed3-area {
            grid-column: 2;
            grid-row: 2;
            background: #fff8e1;
            display: grid;
            grid-template-columns: repeat(3, minmax(0, 1fr));
            grid-template-rows: repeat(4, minmax(0, 1fr));
            gap: 4px;
        }

        /* 大人数模式下的铺位区样式 */
        .bed3-area.large-mode {
            grid-template-columns: repeat(4, minmax(0, 1fr));
            grid-template-rows: repeat(4, minmax(0, 1fr));
        }

        .bed-wash-area {
            grid-column: 1;
            grid-row: 1;
            background: #e3f2fd;
            display: flex;
            align-items: center;
            justify-content: center;
        }
        
        /* 值班表区样式 - 第3列第1行 */
        .schedule-section {
            grid-column: 3;
            grid-row: 1;
            border: 1px solid #000;
            padding: 2px;
            overflow: hidden;
            max-height: 100%;
            display: flex;
            flex-direction: column;
        }
        
        .schedule-table {
            width: 100%;
            border-collapse: collapse;
            height: 100%;
            table-layout: fixed;
        }
        
        .schedule-table th, .schedule-table td {
            border: 1px solid #ddd;
            padding: 2px;
            text-align: center;
            font-size: 12px;
        }
        
        .schedule-table th {
            background-color: #f5f5f5;
            font-weight: bold;
            height: 30px;
        }
        
        .schedule-table tbody {
            height: calc(100% - 30px);
        }
        
        .schedule-table tbody tr {
            height: calc((100% - 30px) / var(--row-count, 3));
        }
        
        /* 待定区样式 - 第3列第2行 */
        .flexible-section {
            grid-column: 3;
            grid-row: 2;
            border: 1px solid #000;
            padding: 10px;
            overflow: hidden;
            max-height: 100%;
        }
        
        /* 单元格通用样式 */
        .cell {
            border: 1px solid #ddd;
            min-height: 25px;
            height: auto;
            background: white;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 14px;
            color: #333;
            line-height: 1.2;
            padding: 3px;
            text-align: center;
            border-radius: 3px;
            overflow: hidden;
            margin: 2px 0;
        }
        
        .empty-cell {
            background: #f9f9f9;
            border: 1px dashed #ddd;
            color: #999;
        }
        
        .cell-name {
            font-weight: bold;
        }
        @media print {
            @page {
                size: A4 landscape;
                margin: 0.1cm;
            }
            
            body {
                margin: 0;
                padding: 0.1cm;
                font-size: 14px;
                -webkit-print-color-adjust: exact;
                print-color-adjust: exact;
            }
            
            .section-header {
                background-color: #f0f0f0 !important;
                -webkit-print-color-adjust: exact;
            }
            
            .cell, .schedule-table th {
                background-color: white !important;
                -webkit-print-color-adjust: exact;
            }
            
            .print-container {
                page-break-inside: avoid;
            }
            
            .cell {
                page-break-inside: avoid;
            }
            
            .no-print {
                display: none !important;
            }
        }
    </style>
</head>
<body>
    <div class="print-container">
        <!-- 座位区 -->
        <div class="seat-section">
            <div class="section-header">座位表</div>
            <div class="seat">
                <div class="area wash-area" data-name="卫生区">卫生区</div>
                <div class="area seat1-area" id="seat1-area"></div>
                <div class="area tunnel-area" data-name="过道">过道</div>
                <div class="area box-area" data-name="储物区">储物区</div>
                <div class="area seat2-area" id="seat2-area"></div>
            </div>
        </div>
        
        <!-- 铺位区 -->
        <div class="bed-section">
            <div class="section-header">铺位表</div>
            <div class="bed">
                <div class="area bed-wash-area" data-name="卫生区">卫生区</div>
                <div class="area bed1-area" id="bed1-area"></div>
                <div class="area bed2-area" id="bed2-area"></div>
                <div class="area bed3-area" id="bed3-area"></div>
            </div>    
        </div>
  
        <!-- 值班表区 -->
        <div class="schedule-section">
            <div class="section-header">值班安排表</div>
            <div style="overflow: hidden; height: calc(100% - 36px);">
                {% set week_info = week_info|default({'day_labels': ['周一','周二','周三','周四','周五','周六','周日'], 'monday': {'formatted_date': '2023年01月01日'}}) %}
                {% set schedule = schedule|default([]) %}
                {% set time_slots = time_slots|default(['早班','中班','晚班']) %}
                <table class="schedule-table" style="width: 100%; border-collapse: collapse; font-size: 14px;">
                    <thead>
                        <tr>
                            <th style="width: 9%;">班次</th>
                            {% for day in week_info.day_labels %}
                            <th style="width: 13%;">{{ day }}</th>
                            {% endfor %}
                        </tr>
                    </thead>
                    <tbody>
                        {% for shift in time_slots %}
                        <tr>
                            <td>{{ shift }}</td>
                            {% for day in schedule %}
                            <td>
                                {% for person in day.shifts.get(shift, []) %}
                                    <div>{{ person.name }}</div>
                                {% else %}
                                    <div style="color: #999; font-style: italic;">(空)</div>
                                {% endfor %}
                            </td>
                            {% else %}
                            <td colspan="{{ week_info.day_labels|length }}">
                                <div style="color: #999; font-style: italic; text-align: center;">无值班安排数据</div>
                            </td>
                            {% endfor %}
                        </tr>
                        {% endfor %}
                    </tbody>
                </table>
            </div>
        </div>
        
        <!-- 注意事项区 -->
        <div class="flexible-section">
            <div class="section-header">注意事项</div>
            <div style="padding: 10px; font-size: 14px;">
                <ul style="margin-left: 15px; line-height: 1.5;">
                    <li>请按时交接班，不得迟到早退</li>
                    <li>保持监室整洁，物品摆放有序</li>
                    <li>发现问题及时报告值班民警</li>
                    <li>严格遵守监室管理规定</li>
                </ul>
                <div style="margin-top: 20px; border-top: 1px dashed #ccc; padding-top: 15px;">
                    <p>值班民警：________________</p>
                    <p style="margin-top: 25px;">日期：{{ week_info.monday.formatted_date if week_info and week_info.monday else '2023年01月01日' }}</p>
                </div>
            </div>
        </div>
    </div>

    <script>
        const backendBedData = {{ bed_data|tojson }};
        const backendSeatData = {{ seat_data|tojson }};
        // 铺位和座位布局数据
        let bedLayoutData = backendBedData || [];
        let seatLayoutData = backendSeatData || [];

        // 渲染铺位和座位布局
        function renderLayouts() {
            renderBedLayout();
            renderSeatLayout();
            setupScheduleTable();
        }
        
        // 设置值班表行高平均分配
        function setupScheduleTable() {
            const scheduleTable = document.querySelector('.schedule-table');
            if (!scheduleTable) return;
            
            const timeSlots = {{ time_slots|default(['早班','中班','晚班'])|tojson }};
            const rowCount = timeSlots.length;
            
            // 设置CSS变量来控制行高
            scheduleTable.style.setProperty('--row-count', rowCount);
        }

        // 渲染座位布局
        function renderSeatLayout() {
            const seat1Area = document.getElementById('seat1-area');
            const seat2Area = document.getElementById('seat2-area');

            if (!seat1Area || !seat2Area) return;

            // 清空现有内容
            seat1Area.innerHTML = '';
            seat2Area.innerHTML = '';
            
            // 判断是否启用大人数模式（超过25人）
            const isLargeMode = seatLayoutData.length > 25;
            
            // 根据模式设置CSS类
            if (isLargeMode) {
                seat1Area.classList.add('large-mode');
                seat2Area.classList.add('large-mode');
            } else {
                seat1Area.classList.remove('large-mode');
                seat2Area.classList.remove('large-mode');
            }
            
            // 根据模式确定布局参数
            let seat1Rows, seat1Cols, seat2Rows, seat2Cols;
            
            if (isLargeMode) {
                // 大人数模式：左侧11行3列（包括被子列），右侧9行2列
                seat1Rows = 11;
                seat1Cols = 3; // 包括被子列
                seat2Rows = 9;
                seat2Cols = 2;
            } else {
                // 标准模式：左侧9行3列（包括被子列），右侧9行1列
                seat1Rows = 9;
                seat1Cols = 3; // 包括被子列
                seat2Rows = 9;
                seat2Cols = 1;
            }
            
            // 创建"被子"单元格函数
            function createBedCell() {
                const cell = document.createElement('div');
                cell.className = 'cell';
                
                const cellContent = document.createElement('div');
                cellContent.className = 'cell-content';
                
                const nameDiv = document.createElement('div');
                nameDiv.className = 'cell-name';
                nameDiv.textContent = '被子';
                
                cellContent.appendChild(nameDiv);
                cell.appendChild(cellContent);
                cell.style.backgroundColor = '#e6f7ff'; // 给被子单元格一个特殊的背景色
                
                return cell;
            }
            
            // 创建一个倒序的人员数据数组
            const reversedData = [...seatLayoutData].reverse();
            
            // 计算seat1区域可容纳的人数（不包括被子列）
            const seat1Capacity = seat1Rows * (seat1Cols - 1); // 减去被子列
            
            // 创建一个二维数组来表示左侧网格(seat1)
            const grid1 = Array(seat1Rows).fill().map(() => Array(seat1Cols).fill(null));
            
            // 首先填充seat1区域
            // 1. 最左侧一列固定为被子区
            for (let row = 0; row < seat1Rows; row++) {
                grid1[row][0] = createBedCell();
            }
            
            // 2. 第二、第三列为人员区，按照"之"字形排列（先左后右，再下一行先左后右）
            let seat1PersonCount = 0;
            for (let row = 0; row < seat1Rows && seat1PersonCount < Math.min(seat1Capacity, reversedData.length); row++) {
                // 先放左边（第2列）
                if (seat1PersonCount < Math.min(seat1Capacity, reversedData.length)) {
                    grid1[row][1] = createLayoutCell(seat1PersonCount, reversedData);
                    seat1PersonCount++;
                }
                
                // 再放右边（第3列）
                if (seat1PersonCount < Math.min(seat1Capacity, reversedData.length)) {
                    grid1[row][2] = createLayoutCell(seat1PersonCount, reversedData);
                    seat1PersonCount++;
                }
            }
            
            // 按照网格顺序添加单元格到seat1Area
            for (let row = 0; row < seat1Rows; row++) {
                for (let col = 0; col < seat1Cols; col++) {
                    if (grid1[row][col]) {
                        seat1Area.appendChild(grid1[row][col]);
                    }
                }
            }
            
            // 如果seat1区域已满，剩余人员放入seat2区域
            if (seat1PersonCount < reversedData.length) {
                // 创建一个二维数组来表示右侧网格(seat2)
                const grid2 = Array(seat2Rows).fill().map(() => Array(seat2Cols).fill(null));
                
                // 按照"之"字形排列（先左后右，再下一行先左后右）
                let seat2PersonCount = 0;
                for (let row = 0; row < seat2Rows && (seat1PersonCount + seat2PersonCount) < reversedData.length; row++) {
                    // 填充每一行的单元格
                    for (let col = 0; col < seat2Cols && (seat1PersonCount + seat2PersonCount) < reversedData.length; col++) {
                        grid2[row][col] = createLayoutCell(seat1PersonCount + seat2PersonCount, reversedData);
                        seat2PersonCount++;
                    }
                }
                
                // 按照网格顺序添加单元格到seat2Area
                for (let row = 0; row < seat2Rows; row++) {
                    for (let col = 0; col < seat2Cols; col++) {
                        if (grid2[row][col]) {
                            seat2Area.appendChild(grid2[row][col]);
                        }
                    }
                }
            }
        }

        // 渲染铺位布局
        function renderBedLayout() {
            const bed1Area = document.getElementById('bed1-area');
            const bed2Area = document.getElementById('bed2-area');
            const bed3Area = document.getElementById('bed3-area');

            if (!bed1Area || !bed2Area || !bed3Area) return;

            // 清空现有内容
            bed1Area.innerHTML = '';
            bed2Area.innerHTML = '';
            bed3Area.innerHTML = '';
            
            // 判断是否启用大人数模式（超过25人）
            const isLargeMode = bedLayoutData.length > 25;
            
            // 根据模式设置CSS类
            if (isLargeMode) {
                bed1Area.classList.add('large-mode');
                bed2Area.classList.add('large-mode');
                bed3Area.classList.add('large-mode');
            } else {
                bed1Area.classList.remove('large-mode');
                bed2Area.classList.remove('large-mode');
                bed3Area.classList.remove('large-mode');
            }
            
            // 根据模式确定布局参数
            let bed1Rows, bed2Rows, bed3Rows, bed3Cols;
            
            if (isLargeMode) {
                // 大人数模式：左侧15行1列，右上5行1列，右下4列4行
                bed1Rows = 15;
                bed2Rows = 5;
                bed3Rows = 4;
                bed3Cols = 4;
            } else {
                // 标准模式：左侧13行1列，右上3行1列，右下3列4行
                bed1Rows = 13;
                bed2Rows = 3;
                bed3Rows = 4;
                bed3Cols = 3;
            }
            
            // 1. 渲染铺位到bed1Area（从下往上）- 保持不变
            // 创建一个临时数组来存储单元格
            const bed1Cells = [];
            for (let i = 0; i < Math.min(bed1Rows, bedLayoutData.length); i++) {
                bed1Cells.push(createLayoutCell(i, bedLayoutData));
            }
            
            // 从下往上添加到bed1Area
            for (let i = bed1Cells.length - 1; i >= 0; i--) {
                bed1Area.appendChild(bed1Cells[i]);
            }
            
            // 计算已分配的人数
            let assignedCount = bed1Rows;
            
            // 2. 渲染铺位到bed3Area（一行一行，每行从右往左）
            // 创建一个二维数组来表示网格
            const grid3 = Array(bed3Rows).fill().map(() => Array(bed3Cols).fill(null));
            
            // 计算bed3区域可容纳的人数
            const bed3Capacity = bed3Rows * bed3Cols;
            
            // 按照一行一行，每行从右往左的顺序填充网格
            let cellIndex3 = 0;
            for (let row = bed3Rows - 1; row >= 0; row--) {  // 从最下面一行开始
                for (let col = bed3Cols - 1; col >= 0; col--) {  // 每行从右往左
                    if (assignedCount + cellIndex3 < bedLayoutData.length && cellIndex3 < bed3Capacity) {
                        grid3[row][col] = createLayoutCell(assignedCount + cellIndex3, bedLayoutData);
                        cellIndex3++;
                    }
                }
            }
            
            // 按照网格顺序添加单元格到bed3Area
            for (let row = 0; row < bed3Rows; row++) {
                for (let col = 0; col < bed3Cols; col++) {
                    if (grid3[row][col]) {
                        bed3Area.appendChild(grid3[row][col]);
                    } else {
                        // 添加空单元格
                        const emptyCell = document.createElement('div');
                        emptyCell.className = 'cell empty-cell';
                        bed3Area.appendChild(emptyCell);
                    }
                }
            }
            
            // 更新已分配的人数
            assignedCount += cellIndex3;
            
            // 3. 剩下的人再从下往上排入bed2
            // 创建一个临时数组来存储单元格
            const bed2Cells = [];
            for (let i = assignedCount; i < Math.min(assignedCount + bed2Rows, bedLayoutData.length); i++) {
                bed2Cells.push(createLayoutCell(i, bedLayoutData));
            }
            
            // 从下往上添加到bed2Area
            for (let i = bed2Cells.length - 1; i >= 0; i--) {
                bed2Area.appendChild(bed2Cells[i]);
            }
        }
        
        function createLayoutCell(index, data) {
            const cell = document.createElement('div');
            const person = data[index];
            
            if (person && person.name) {
                cell.className = 'cell';
                cell.innerHTML = `<div class="cell-name">${person.name}</div>`;
            } else {
                cell.className = 'cell empty-cell';
                cell.innerHTML = `<div class="cell-name">空位</div>`;
            }
            return cell;
        }

        // 自动打印
        window.onload = function() {
            renderLayouts();
            window.setTimeout(function() {
                window.print();
            }, 1000);
        };
    </script>
</body>
</html>